package com.berchen.utils;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.*;

public class CodeUtils {
    
    private CodeUtils(){}

    /**
     * 编码 就是将 字符->字节
     * @param charsetStr
     * @param params
     * @return
     */
    public static byte[] encoding(String charsetStr,String params){


        try {
            Charset charset=Charset.forName(charsetStr);
            CharsetEncoder encoder = charset.newEncoder();

            CharBuffer charBuffer=CharBuffer.allocate(params.toCharArray().length);
            charBuffer.put(params);
            charBuffer.flip();
            // 编码
            ByteBuffer encode= encoder.encode(charBuffer);
            // 编码后的字节数组
            byte[] result=new byte[encode.limit()];
            // 读取流中的数据到字节数组中
            encode.get(result);
            return result;
        }
        catch (MalformedInputException e){
            System.out.println("编码格式错误");
        }
        catch (CharacterCodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解码 就是将 字节->字符
     * @param charsetStr
     * @param params
     * @return
     */
    public static String decoding(String charsetStr,byte[] params){

        try {
            Charset charset = Charset.forName(charsetStr);
            // 获取解码器
            CharsetDecoder decoder = charset.newDecoder();
            ByteBuffer byteBuffer = ByteBuffer.allocate(params.length);
            byteBuffer.put(params);
            byteBuffer.flip();

            // 解码
            CharBuffer decodeStr = decoder.decode(byteBuffer);
            return decodeStr.toString();
        }
        catch (MalformedInputException e){
            System.out.println("编码格式错误");
        }
        catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) throws CharacterCodingException {

        byte[] bytes = encoding("gbk", "陈琬皓");
        System.out.println(new String(bytes));


        System.out.println(decoding("gbk", bytes));
    }

}
